package org.jeecg.modules.system.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.OrderCalcModel;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.vo.OrderCalcVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 *
 * @Author dongw
 */
@Slf4j
@RestController
@RequestMapping("/sys/order")
public class OrderController {

    @Autowired
    private ISysAirProductService airProductService;

    @Autowired
    private ISysLandProductService landProductService;

    @Autowired
    private ISysLessProductService lessProductService;

    @Autowired
    private ISysProductOtherSettingService otherSettingService;

    @Autowired
    private ISysOrderService orderService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 客户订单列表
     *
     * @return
     */
    @GetMapping("/list/owner")
    public Result<List<SysOrder>> list(String startDate, String endDate, String orderNumber, Integer invoiceStatus, Integer isPay) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrder::getCreateBy, sysUser.getUsername());
        if (!StringUtils.isAllBlank(startDate, endDate)) {
            lambdaQueryWrapper.between(SysOrder::getCreateTime, startDate, endDate);
        }
        if (StringUtils.isNotBlank(orderNumber)) {
            lambdaQueryWrapper.and(w -> w.like(SysOrder::getOrderNumber, orderNumber)
                    .or()
                    .like(SysOrder::getSspWorkNo, orderNumber)
                    .or()
                    .like(SysOrder::getDeliverNumber, orderNumber)
            );
        }
        if (null != invoiceStatus) {
            lambdaQueryWrapper.eq(SysOrder::getInvoiceStatus, invoiceStatus);
        }
        if (null != isPay) {
            lambdaQueryWrapper.eq(SysOrder::getIsPay, isPay);
        }
        lambdaQueryWrapper.last("order by ifnull(update_time,create_time) desc");
        List<SysOrder> list = orderService.list(lambdaQueryWrapper);
        return Result.OK(list);
    }

    /**
     * 管理端订单列表
     *
     * @return
     */
    @GetMapping("/list/all")
    public Result<List<SysOrder>> listAll(String startDate, String endDate, String orderNumber, Integer invoiceStatus, String userName,String companyCode,String isPay) {
        LambdaQueryWrapper<SysOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isAllBlank(startDate, endDate)) {
            lambdaQueryWrapper.between(SysOrder::getCreateTime, startDate, endDate);
        }
        if (StringUtils.isNotBlank(orderNumber)) {
            lambdaQueryWrapper.and(w -> w.like(SysOrder::getOrderNumber, orderNumber)
                    .or()
                    .like(SysOrder::getSspWorkNo, orderNumber)
                    .or()
                    .like(SysOrder::getDeliverNumber, orderNumber)
            );
        }
        if (null != invoiceStatus) {
            lambdaQueryWrapper.eq(SysOrder::getInvoiceStatus, invoiceStatus);
        }

        if (StringUtils.isNotBlank(userName)) {
            lambdaQueryWrapper.eq(SysOrder::getCreateBy, userName);
        }
        if (StringUtils.isNotBlank(companyCode)) {
            lambdaQueryWrapper.eq(SysOrder::getCompanyCode, companyCode);
        }
        if (StringUtils.isNotBlank(isPay)) {
            lambdaQueryWrapper.eq(SysOrder::getIsPay, isPay);
        }

        lambdaQueryWrapper.last("order by ifnull(update_time,create_time) desc");
        List<SysOrder> list = orderService.list(lambdaQueryWrapper);
        return Result.OK(list);
    }

    @PostMapping("/editPay")
    public Result editIsPay(@RequestBody SysOrder order){
        if(null==order.getIsPay() || StringUtils.isBlank(order.getId())){
            return Result.error("请求异常！请刷新后重试。");
        }
        orderService.update(Wrappers.<SysOrder>lambdaUpdate()
                .set(SysOrder::getIsPay,order.getIsPay())
                .eq(SysOrder::getId,order.getId())
        );
        return Result.OK();
    }

    @PostMapping("/editOrderConfirm")
    public Result editOrderConfirm(@RequestBody SysOrder order) {
        orderService.update(Wrappers.<SysOrder>lambdaUpdate()
                .set(SysOrder::getOrderConfirm,order.getOrderConfirm())
                .eq(SysOrder::getId,order.getId())
        );
        return Result.OK();
    }

    @PostMapping("/editRate")
    public Result editRate(@RequestBody SysOrder order) {
        BigDecimal linePrice =order.getLinePrice();
        if("陆运大件".equals(order.getTransportProducts())){
            //linePrice
             linePrice = order.getLinePriceOriginal().multiply(order.getLineUnitPrice()).setScale(2, RoundingMode.DOWN);
        }else{
            //linePrice
            linePrice = order.getLineCostPrice().multiply(order.getChargedWeight()).setScale(2, RoundingMode.DOWN);
        }
        order.setLinePrice(linePrice);
        BigDecimal multiply = linePrice.multiply(order.getRate());
        //计算总价 = 干线+国内+保险费
        BigDecimal gnyf = BigDecimal.ZERO;
        BigDecimal bxf = BigDecimal.ZERO;
        if(null!=order.getDomesticFreight()){
            gnyf=order.getDomesticFreight();
        }
        if(null!=order.getInsurePrice()){
            bxf=order.getInsurePrice();
        }

        BigDecimal add = multiply.add(gnyf).add(bxf);
        order.setTotalPrice(add);
        orderService.updateById(order);
//        orderService.update(Wrappers.<SysOrder>lambdaUpdate()
//                .set(SysOrder::getRate, order.getRate())
//                .eq(SysOrder::getId, order.getId())
//        );
        return Result.OK();
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody SysOrder order) {
        orderService.updateById(order);
        return Result.OK();
    }


    /**
     * 订单确认（保存）
     *
     * @param sysOrder
     * @return
     */
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@Valid @RequestBody SysOrder sysOrder, BindingResult result) {
        if (result.hasErrors()) {
            return Result.error(result.getAllErrors().get(0).getDefaultMessage());
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sysOrder.setCompanyCode(sysUser.getCompanyCode());
        String sspNo = getSspNo();
        sysOrder.setSspWorkNo(sspNo);
        orderService.save(sysOrder);
        JSONObject orderJson = new JSONObject();
        orderJson.put("country","RU");
        orderJson.put("consignee_address",sysOrder.getConsigneeAddress());
        orderJson.put("consignee_state",sysOrder.getConsigneeState());
        orderJson.put("order_customerinvoicecode",sysOrder.getId());
        orderJson.put("customer_userid","14021");
        orderJson.put("consignee_name",sysOrder.getConsigneeName());
        orderJson.put("buyerid","");
        orderJson.put("consignee_city",sysOrder.getConsigneeCity());
        orderJson.put("consignee_telephone",sysOrder.getConsigneePhone());
        //2261 2281
        orderJson.put("product_id",sysOrder.getTransportProducts().contains("空运")?"2261":"2281");
        orderJson.put("trade_type","ZYXT");
        orderJson.put("customer_id","17521");
        orderJson.put("consignee_postcode",sysOrder.getConsigneePost());
        orderJson.put("order_insurance",sysOrder.getInsurePrice());
//        orderJson.put("order_piece",sysOrder.getPackageNumber());
        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("invoice_pcs",sysOrder.getPackageNumber());
        jo.put("invoice_title",sysOrder.getGoodsName());
        jo.put("sku",sysOrder.getGoodsName());
        jo.put("invoice_amount",sysOrder.getGoodsValue());//申报总价值=货物货值？
        ja.add(jo);
        orderJson.put("orderInvoiceParam",ja);
        JSONArray ja1 = new JSONArray();
        JSONObject jo1 = new JSONObject();
        jo1.put("volume_height",sysOrder.getHeightValue());
        jo1.put("volume_length",sysOrder.getLongValue());
        jo1.put("volume_width",sysOrder.getWidthValue());
        jo1.put("volume_weight",sysOrder.getGoodsWeight());
        ja1.add(jo1);
        orderJson.put("orderVolumeParam",ja1);
        String jsonString = orderJson.toJSONString();
        System.out.println("jsonString = " + jsonString);
        String orderUrl = "http://47.98.37.135:8082/createOrderApi.htm";
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("param",jsonString);
        String result2 = HttpRequest.post(orderUrl)
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        log.info(result2);
        JSONObject jsonObject = JSONObject.parseObject(result2);
        if("false".equals(jsonObject.getString("ack"))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            try {
                return Result.error(URLDecoder.decode(jsonObject.getString("message"),"utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        sysOrder.setDeliverNumber(jsonObject.getString("tracking_number"));
        sysOrder.setOrderApiInfo(result2);
        orderService.updateById(sysOrder);
        return Result.OK(sysOrder);
    }

    @GetMapping("/queryTrack/{id}")
    public Result queryTrack(@PathVariable String id){
        List<SysOrder> list = orderService.list(Wrappers.<SysOrder>lambdaQuery()
                .eq(SysOrder::getSspWorkNo, id)
                .or()
                .eq(SysOrder::getDeliverNumber, id)
        );
        if(list.size()==0){
            return Result.error("编号在系统中不存在");
        }
        SysOrder sysOrder = list.get(0);
        String deliverNumber = sysOrder.getDeliverNumber();
        String trackUrl = "http://47.98.37.135:8082/selectTrack.htm?documentCode="+deliverNumber;
        String trackResult = HttpRequest.get(trackUrl)
                .execute().body();
        log.info(trackResult);
        JSONArray objects = JSONArray.parseArray(trackResult);
        JSONObject jsonObject = objects.getJSONObject(0);
        String ack = jsonObject.getString("ack");
        if("false".equals(ack)){
            return Result.error("运踪查询失败");
        }else{
            JSONArray data = jsonObject.getJSONArray("data");
            JSONObject jsonObject2 = data.getJSONObject(0);
            JSONArray trackDetails = jsonObject2.getJSONArray("trackDetails");
            JSONObject jsonObject1 = trackDetails.getJSONObject(trackDetails.size() - 1);
            String string1 = jsonObject1.getString("track_date");
            String string2 = jsonObject2.getString("trackDate");
            //在途时间
            long betweenDay = DateUtil.between(DateUtil.parse(string1), DateUtil.parse(string2), DateUnit.DAY);
            if("已收货".equals(jsonObject2.getString("businessStatus"))){
                sysOrder.setWarehousingDate(string2);
                orderService.updateById(sysOrder);
            }
            JSONObject respData = new JSONObject();
            respData.put("data",data);
            respData.put("order",sysOrder);
            respData.put("betweenDay",betweenDay);
            return Result.OK(respData);
        }
    }

    /**
     * 账单确认
     * 新增订单后，管理端会返回本条所有数据。前端直接跳转到“账单&运踪”页面并展示。
     * 如果订单已确认（orderConfirm=1）在“账单&运踪”页中不显示账单确认按钮。
     *
     * @param id
     * @return
     */
    @PostMapping("/orderConfirm/{id}")
    public Result orderConfirm(@PathVariable String id) {
        orderService.update(Wrappers.<SysOrder>lambdaUpdate()
                .eq(SysOrder::getId, id)
                .set(SysOrder::getOrderConfirm, 1)
        );
        return Result.OK().success("账单已确认");
    }


    private synchronized String getSspNo() {
        int i = DateUtil.thisYear();
        int i1 = DateUtil.thisMonth() + 1;
        long count = orderService.count(Wrappers.<SysOrder>lambdaQuery()
                .likeRight(SysOrder::getSspWorkNo,"SSP" + i + (i1 < 10 ? ("0" + i1) : i1) )
        );
        String formattedNumber = String.format("%05d", count+1);
        return "SSP" + i + (i1 < 10 ? ("0" + i1) : i1) + "9" + formattedNumber;
    }


    /**
     * 费用计算
     *
     * @param type
     * @param model
     * @return
     */
    @PostMapping("/calcFee/{type}")
    public Result<OrderCalcVO> calcFee(@PathVariable String type, @RequestBody OrderCalcModel model) {
        if (null == model.getVolume() || null == model.getGoodsWeight()) {
            return Result.error("参数异常");
        }
        Object o = redisUtil.get("rate:" + DateUtil.today());
        BigDecimal rate = BigDecimal.ONE;
        OrderCalcVO orderCalcVO = new OrderCalcVO();
        if (type.equals("less")) {
            if (null == o && null==model.getRate()) {
                try {
                    String s = HttpRequest.get("http://op.juhe.cn/onebox/exchange/currency?from=USD&to=CNY&key=107f9230bfbf817ee8b980e1a94669c2").execute().body();
                    JSONArray result = JSONObject.parseObject(s).getJSONArray("result");
                    rate = result.getJSONObject(0).getBigDecimal("exchange");
                    redisUtil.set("rate:" + DateUtil.today(), rate);
                } catch (Exception e) {
                    e.printStackTrace();
                    rate = new BigDecimal("7.31");
                }
            } else {
                rate = new BigDecimal(o.toString());
            }
            BigDecimal divide = model.getGoodsWeight().divide(model.getVolume(), 2, BigDecimal.ROUND_DOWN);
            BigDecimal calcUnit = model.getVolume();
            //大于等于100
            if (divide.compareTo(new BigDecimal(100)) >= 0) {
                calcUnit = model.getGoodsWeight();
            }
            List<SysLessProduct> matchProducts = lessProductService.matchProducts(divide);
            if (matchProducts.size() > 1) {
                return Result.error("匹配产品失败，匹配到多个产品");
            } else if (matchProducts.size() == 0) {
                return Result.error("匹配产品失败，未匹配到产品");
            }
            SysLessProduct sysLessProduct = matchProducts.get(0);
            BigDecimal showPrice = sysLessProduct.getMowShowPrice();
            BigDecimal lineCostPrice = sysLessProduct.getMowCostPrice();
            if (!model.getDeliveryPlace().equals("莫斯科")) {
                showPrice = sysLessProduct.getMowOutShowPrice();
                lineCostPrice = sysLessProduct.getMowOutCostPrice();
            }
            if (null == showPrice) {
                showPrice = BigDecimal.ZERO;
            }
            //美金转换成人民币
            BigDecimal convert = showPrice.multiply(rate).setScale(2, RoundingMode.DOWN);
            BigDecimal multiply = calcUnit.multiply(convert).setScale(2, RoundingMode.DOWN);
            orderCalcVO.setFreightCoefficient(sysLessProduct.getResetFilter());
            orderCalcVO.setLineUnitPrice(showPrice);
            orderCalcVO.setLinePrice(multiply);
            orderCalcVO.setRate(rate);
            orderCalcVO.setLineCostPrice(lineCostPrice);
            orderCalcVO.setLinePriceOriginal(calcUnit);
        } else {
            orderCalcVO.setRate(rate);
            SysProductOtherSetting one = otherSettingService.getOne(Wrappers.<SysProductOtherSetting>lambdaQuery().eq(SysProductOtherSetting::getType, type));
            Integer zpbInt = 0;
            try {
                String zpb = one.getZpb().replaceAll("1:", "");
                zpbInt = Integer.valueOf(zpb);
            } catch (Exception e) {
                return Result.error("重泡比设置异常");
            }
            //x=体积*1000000
            BigDecimal multiply = model.getVolume().multiply(new BigDecimal(1000000));
            //x/重泡比
            BigDecimal bigDecimal = new BigDecimal(zpbInt);
            BigDecimal divide = multiply.divide(bigDecimal, 2, BigDecimal.ROUND_DOWN);
            //计费重量
            BigDecimal jfzl = model.getGoodsWeight();
            if (model.getGoodsWeight().compareTo(divide) < 0) {
                jfzl = divide;
            }
            if (type.equals("air")) {
                List<SysAirProduct> matchProducts = airProductService.matchProduct(jfzl);

                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }

                SysAirProduct sysAirProduct = matchProducts.get(0);
                BigDecimal showPrice = sysAirProduct.getShowPrice();
                if (null == showPrice) {
                    showPrice = BigDecimal.ZERO;
                }
                //货物价值
                BigDecimal multiply1 = showPrice.multiply(jfzl);

                orderCalcVO.setChargedWeight(jfzl);
                orderCalcVO.setLinePrice(multiply1);
                orderCalcVO.setLineUnitPrice(showPrice);
                orderCalcVO.setInsureRate(one.getBxfl());
                orderCalcVO.setLinePriceOriginal(BigDecimal.ZERO);
                orderCalcVO.setLineCostPrice(sysAirProduct.getCostPrice());
            } else {
                List<SysLandProduct> matchProducts = landProductService.matchProducts(jfzl);
                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }
                SysLandProduct sysLandProduct = matchProducts.get(0);
                BigDecimal showPrice = sysLandProduct.getMowShowPrice();
                BigDecimal lineCostPrice = sysLandProduct.getMowCostPrice();
                if (!model.getDeliveryPlace().equals("莫斯科")) {
                    showPrice = sysLandProduct.getMowOutShowPrice();
                    lineCostPrice = sysLandProduct.getMowOutCostPrice();
                }
                if (null == showPrice) {
                    showPrice = BigDecimal.ZERO;
                }

                //货物价值
                BigDecimal multiply1 = showPrice.multiply(jfzl);
                orderCalcVO.setChargedWeight(jfzl);
                orderCalcVO.setLinePrice(multiply1);
                orderCalcVO.setLineUnitPrice(showPrice);
                orderCalcVO.setInsureRate(one.getBxfl());
                orderCalcVO.setLinePriceOriginal(BigDecimal.ZERO);
                orderCalcVO.setLineCostPrice(lineCostPrice);
            }
        }
        return Result.OK(orderCalcVO);
    }
    /**
     * 费用计算
     *
     * @param type
     * @param model
     * @return
     */
    @PostMapping("/reCalcFee/{type}")
    public Result<OrderCalcVO> reCalcFee(@PathVariable String type, @RequestBody OrderCalcModel model) {
        if (null == model.getVolume() || null == model.getGoodsWeight()) {
            return Result.error("参数异常");
        }
        OrderCalcVO orderCalcVO = new OrderCalcVO();
        if (type.equals("less")) {
            BigDecimal divide = model.getGoodsWeight().divide(model.getVolume(), 2, BigDecimal.ROUND_DOWN);
            BigDecimal calcUnit = model.getVolume();
            //大于等于100
            if (divide.compareTo(new BigDecimal(100)) >= 0) {
                calcUnit = model.getGoodsWeight();
            }
            List<SysLessProduct> matchProducts = lessProductService.matchProducts(divide);
            if (matchProducts.size() > 1) {
                return Result.error("匹配产品失败，匹配到多个产品");
            } else if (matchProducts.size() == 0) {
                return Result.error("匹配产品失败，未匹配到产品");
            }
            SysLessProduct sysLessProduct = matchProducts.get(0);
            BigDecimal showPrice = sysLessProduct.getMowShowPrice();
            BigDecimal lineCostPrice = sysLessProduct.getMowCostPrice();
            if (!model.getDeliveryPlace().equals("莫斯科")) {
                showPrice = sysLessProduct.getMowOutShowPrice();
                lineCostPrice = sysLessProduct.getMowOutCostPrice();
            }
            if (null == showPrice) {
                showPrice = BigDecimal.ZERO;
            }
            //美金转换成人民币
            BigDecimal convert = showPrice.multiply(model.getRate()).setScale(2, RoundingMode.DOWN);
            BigDecimal multiply = calcUnit.multiply(convert).setScale(2, RoundingMode.DOWN);
            orderCalcVO.setFreightCoefficient(sysLessProduct.getResetFilter());
            orderCalcVO.setLineUnitPrice(showPrice);
            orderCalcVO.setLinePrice(multiply);
            orderCalcVO.setRate(model.getRate());
            orderCalcVO.setLineCostPrice(lineCostPrice);
            orderCalcVO.setLinePriceOriginal(calcUnit);
        } else {
            orderCalcVO.setRate(model.getRate());
            SysProductOtherSetting one = otherSettingService.getOne(Wrappers.<SysProductOtherSetting>lambdaQuery().eq(SysProductOtherSetting::getType, type));
            Integer zpbInt = 0;
            try {
                String zpb = one.getZpb().replaceAll("1:", "");
                zpbInt = Integer.valueOf(zpb);
            } catch (Exception e) {
                return Result.error("重泡比设置异常");
            }
            //x=体积*1000000
            BigDecimal multiply = model.getVolume().multiply(new BigDecimal(1000000));
            //x/重泡比
            BigDecimal bigDecimal = new BigDecimal(zpbInt);
            BigDecimal divide = multiply.divide(bigDecimal, 2, BigDecimal.ROUND_DOWN);
            //计费重量
            BigDecimal jfzl = model.getGoodsWeight();
            if (model.getGoodsWeight().compareTo(divide) < 0) {
                jfzl = divide;
            }
            if (type.equals("air")) {
                List<SysAirProduct> matchProducts = airProductService.matchProduct(jfzl);

                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }

                SysAirProduct sysAirProduct = matchProducts.get(0);
                BigDecimal showPrice = sysAirProduct.getShowPrice();
                if (null == showPrice) {
                    showPrice = BigDecimal.ZERO;
                }
                //货物价值
                BigDecimal multiply1 = showPrice.multiply(jfzl);
                BigDecimal convert = multiply1.multiply(model.getRate()).setScale(2, RoundingMode.DOWN);
                orderCalcVO.setChargedWeight(jfzl);
                orderCalcVO.setLinePrice(convert);
                orderCalcVO.setLineUnitPrice(showPrice);
                orderCalcVO.setInsureRate(one.getBxfl());
                orderCalcVO.setLinePriceOriginal(BigDecimal.ZERO);
                orderCalcVO.setLineCostPrice(sysAirProduct.getCostPrice());
            } else {
                List<SysLandProduct> matchProducts = landProductService.matchProducts(jfzl);
                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }
                SysLandProduct sysLandProduct = matchProducts.get(0);
                BigDecimal showPrice = sysLandProduct.getMowShowPrice();
                BigDecimal lineCostPrice = sysLandProduct.getMowCostPrice();
                if (!model.getDeliveryPlace().equals("莫斯科")) {
                    showPrice = sysLandProduct.getMowOutShowPrice();
                    lineCostPrice = sysLandProduct.getMowOutCostPrice();
                }
                if (null == showPrice) {
                    showPrice = BigDecimal.ZERO;
                }

                //货物价值
                BigDecimal multiply1 = showPrice.multiply(jfzl);
                BigDecimal convert = multiply1.multiply(model.getRate()).setScale(2, RoundingMode.DOWN);
                orderCalcVO.setChargedWeight(jfzl);
                orderCalcVO.setLinePrice(convert);
                orderCalcVO.setLineUnitPrice(showPrice);
                orderCalcVO.setInsureRate(one.getBxfl());
                orderCalcVO.setLinePriceOriginal(BigDecimal.ZERO);
                orderCalcVO.setLineCostPrice(lineCostPrice);
            }
        }
        return Result.OK(orderCalcVO);
    }

    @PostMapping("/getParam/{type}")
    public Result getParam(@PathVariable String type, @RequestBody OrderCalcModel model) {
        if (null == model.getVolume() || null == model.getGoodsWeight()) {
            return Result.error("参数异常");
        }
        if (type.equals("less")) {
            BigDecimal divide = model.getGoodsWeight().divide(model.getVolume(), 2, BigDecimal.ROUND_DOWN);
            List<SysLessProduct> matchProducts = lessProductService.matchProducts(divide);
            if (matchProducts.size() > 1) {
                return Result.error("匹配产品失败，匹配到多个产品");
            } else if (matchProducts.size() == 0) {
                return Result.error("匹配产品失败，未匹配到产品");
            }
            SysLessProduct sysLessProduct = matchProducts.get(0);
            return Result.OK(sysLessProduct.getResetFilter());
        } else {
            SysProductOtherSetting one = otherSettingService.getOne(Wrappers.<SysProductOtherSetting>lambdaQuery().eq(SysProductOtherSetting::getType, type));
            Integer zpbInt = 0;
            try {
                String zpb = one.getZpb().replaceAll("1:", "");
                zpbInt = Integer.valueOf(zpb);
            } catch (Exception e) {
                return Result.error("重泡比设置异常");
            }
            //x=体积*1000000
            BigDecimal multiply = model.getVolume().multiply(new BigDecimal(1000000));
            //x/重泡比
            BigDecimal bigDecimal = new BigDecimal(zpbInt);
            BigDecimal divide = multiply.divide(bigDecimal, 2, BigDecimal.ROUND_DOWN);
            //计费重量
            BigDecimal jfzl = model.getGoodsWeight();
            if (model.getGoodsWeight().compareTo(divide) < 0) {
                jfzl = divide;
            }
            if (type.equals("air")) {
                List<SysAirProduct> matchProducts = airProductService.matchProduct(jfzl);
                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }
            } else {
                List<SysLandProduct> matchProducts = landProductService.matchProducts(jfzl);
                if (matchProducts.size() > 1) {
                    return Result.error("匹配产品失败，匹配到多个产品");
                } else if (matchProducts.size() == 0) {
                    return Result.error("匹配产品失败，未匹配到产品");
                }
            }
            return Result.OK(jfzl);
        }
    }

    public static void main(String[] args) {
        String strParam="{\n" +
                "\t\"country\": \"RU\",\n" +
                "\t\"consignee_address\": \"РОССИЯ, Московская область, Чеховский район, г. Чехов, Симферопольское шоссе, д. 2\",\n" +
                "\t\"consignee_state\": \"Московская область\",\n" +
                "\t\"order_customerinvoicecode\": \"1724377499871260674\",\n" +
                "\t\"customer_userid\": \"14021\",\n" +
                "\t\"consignee_name\": \"Михаил Поливсев\",\n" +
                "\t\"orderVolumeParam\": [{\n" +
                "\t\t\"volume_length\": 15.00,\n" +
                "\t\t\"volume_height\": 25.00,\n" +
                "\t\t\"volume_weight\": 10.00,\n" +
                "\t\t\"volume_width\": 35.00\n" +
                "\t}],\n" +
                "\t\"buyerid\": \"\",\n" +
                "\t\"consignee_city\": \"Чеховский район\",\n" +
                "\t\"order_piece\": 2,\n" +
                "\t\"consignee_telephone\": \"+7 (926)  462 10 40\",\n" +
                "\t\"product_id\": \"2261\",\n" +
                "\t\"order_insurance\": 25,\n" +
                "\t\"trade_type\": \"ZYXT\",\n" +
                "\t\"customer_id\": \"17521\",\n" +
                "\t\"consignee_postcode\": \"142300\",\n" +
                "\t\"orderInvoiceParam\": [{\n" +
                "\t\t\"invoice_title\": \"笔记本\",\n" +
                "\t\t\"sku\": \"笔记本\",\n" +
                "\t\t\"invoice_pcs\": 2,\n" +
                "\t\t\"invoice_amount\": 1000.00\n" +
                "\t}]\n" +
                "}";

        String orderUrl = "http://47.98.37.135:8082/createOrderApi.htm";
        String authUrl = "http://47.98.37.135:8082/selectAuth.htm?username=SSP RU&password=123456";
        String productUrl = "http://47.98.37.135:8082/getProductList.htm";
        String trackUrl = "http://47.98.37.135:8082/selectTrack.htm?documentCode=ZJRU04100050QG";

//        Map<String,Object> paramMap = new HashMap<>();
//        paramMap.put("param",strParam);
//        String result2 = HttpRequest.post(orderUrl)
//                .form(paramMap)//表单内容
//                .timeout(20000)//超时，毫秒
//                .execute().body();
//        System.out.println("result2 = " + result2);
//        JSONObject jsonObject = JSONObject.parseObject(result2);
//        if("false".equals(jsonObject.getString("ack"))){
//            try {
//                System.out.println(URLDecoder.decode(jsonObject.getString("message"),"utf-8"));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }

        /**
         *
         * {
         * 	"express_type": "ZX",
         * 	"print_minor_languages": "",
         * 	"product_doornorule": "",
         * 	"product_id": "2261",
         * 	"product_note": "",
         * 	"product_shortname": "快空",
         * 	"product_shortnumber": "",
         * 	"product_tracknoapitype": ""
         * }, {
         * 	"express_type": "ZX",
         * 	"print_minor_languages": "N",
         * 	"product_doornorule": "",
         * 	"product_id": "2281",
         * 	"product_note": "",
         * 	"product_shortname": "经济小包",
         * 	"product_shortnumber": "",
         * 	"product_tracknoapitype": ""
         * }
         *
         */
        String trackResult = HttpRequest.get(trackUrl)
                .execute().body();
        System.out.println("productResult = " + trackResult);
//        String productResult = HttpRequest.get(productUrl)
//                .execute().body();
//        System.out.println("productResult = " + productResult);
//        String result2 = HttpRequest.get(authUrl)
//                .execute().body();
//        //'customer_id':'17521','customer_userid':'14021'
//        System.out.println("result2 = " + result2);
//        JSONObject jsonObject = JSONObject.parseObject(strParam);
//        System.out.println("jsonObject = " + jsonObject);

//        HttpClient objClient = new HttpClient();
//        objClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//
//        PostMethod objPostMethod = new PostMethod(strUrl);
//
//        try {
//            strParam=URLEncoder.encode(strParam,"UTF-8");
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//        NameValuePair objNameValuePair = new NameValuePair();
//        objNameValuePair.setName("param");
//        objNameValuePair.setValue(strParam);
//        objPostMethod.addParameter(objNameValuePair);
//        try {
//            int statusCode = objClient.executeMethod(objPostMethod);
//
//            String strResponseBody = new String(objPostMethod.getResponseBody());
//            System.out.println("createOrder:statusCode~~~~~" + statusCode);
//            System.out.println("createOrder:strResponseBody~~~~~" + strResponseBody);
//        }catch(Exception e)
//        {
//
//        }
//
//        try {
//            System.out.println(URLDecoder.decode("%E7%89%B9%E6%AE%8A%E5%AD%97%E7%AC%A6%E6%97%A0%E6%B3%95%E8%A7%A3%E6%9E%90%21","utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

    }

}
